﻿
using Dt261.db;
using Dt261.Model;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Panuon.UI.Silver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace Dt261.ViewModel
{
    class UserInfoViewModel : ViewModelBase
    {

        private MemberInfoDb db;
        // UserDb userDB;
        private MemberInfo selectMember;

        private string name;//姓名
        private string phone;//电话
        private string age;//年龄
        private string zhiye;//职业
        private bool isGirl;//性别
        private DateTime bday;


        private string idCard;//身份证号
        private string insurance;//编号

        private string address;//地址
        private string zipCode;//邮编

        private string allergyHistory;//过敏史
        private string history;//疾病历史

        private string deafAidRoutine;//中耳炎
        private string deafAidThreshold;//助听听阀
        private string soundField;//s声场

        private string tinnitus;//耳鸣匹配      
        private string strength;//强度
        private string deafAidLeftModel;//助听器型号左
        private string deafAidRightModel;//助听器型号右


        private string deafAidVolume;//音量
                                     // 
        private string deviceWT;//型号
        private string chengxu;// 程序


        private string mark;//备注


        public RelayCommand CancelAddMemberCommand { get; set; }
        public RelayCommand SaveMemberCommand { get; set; }
        public UserInfoViewModel()
        {
            CancelAddMemberCommand = new RelayCommand(CancelAddMember);
            SaveMemberCommand = new RelayCommand(SaveMember);

            db = new MemberInfoDb(dbconfig.DatabasePath);
            // userDB = new UserDb(dbconfig.DatabasePath);
            Bday = DateTime.Now;
            // Age = 20;
        }

        public MemberInfo SelectMember
        {
            get => selectMember;
            set
            {
                selectMember = value;
                Name = selectMember.Name;
                Phone = selectMember.Phone;
                Mark = selectMember.Mark;
                Zhiye = selectMember.Note;
                Bday = selectMember.Birthday;
                IsGirl = selectMember.Gender == 1 ? true : false;
                Age = selectMember.Age.ToString();

                if (selectMember.Age == 0 && Bday != null)
                {
                    Age = (DateTime.Now.Year - Bday.Year).ToString();
                }
                IdCard = selectMember.IdCard;
                Insurance = selectMember.Insurance;
                Address = selectMember.Address;
                ZipCode = selectMember.ZipCode;
                AllergyHistory = selectMember.AllergyHistory;
                History = selectMember.History;
                DeafAidRoutine = selectMember.DeafAidRoutine;
                DeafAidThreshold = selectMember.DeafAidThreshold;
                SoundField = selectMember.SoundField;
                Tinnitus = selectMember.Tinnitus;
                Strength = selectMember.Strength;
                DeafAidLeftModel = selectMember.DeafAidLeftModel;
                DeafAidRightModel = selectMember.DeafAidRightModel;
                DeafAidVolume = selectMember.DeafAidVolume;
                DeviceWT = selectMember.DeviceWT;
                Chengxu = selectMember.Note;
            }
        }

        public string Name { get => name; set { name = value; RaisePropertyChanged(); } }
        public string Phone { get => phone; set { phone = value; RaisePropertyChanged(); } }
        public string Zhiye { get => zhiye; set { zhiye = value; RaisePropertyChanged(); } }
        public bool IsGirl { get => isGirl; set { isGirl = value; RaisePropertyChanged(); } }
        public DateTime Bday { get => bday; set { bday = value; RaisePropertyChanged(); } }
        public string Mark { get => mark; set { mark = value; RaisePropertyChanged(); } }

        public string Age { get => age; set { age = value; RaisePropertyChanged(); } }


        public string Insurance { get => insurance; set { insurance = value; RaisePropertyChanged(); } }
        public string Address { get => address; set { address = value; RaisePropertyChanged(); } }
        public string IdCard { get => idCard; set { idCard = value; RaisePropertyChanged(); } }
        public string ZipCode { get => zipCode; set { zipCode = value; RaisePropertyChanged(); } }
        public string AllergyHistory { get => allergyHistory; set { allergyHistory = value; RaisePropertyChanged(); } }
        public string History { get => history; set { history = value; RaisePropertyChanged(); } }
        public string DeafAidRoutine { get => deafAidRoutine; set { deafAidRoutine = value; RaisePropertyChanged(); } }
        public string DeafAidThreshold { get => deafAidThreshold; set { deafAidThreshold = value; RaisePropertyChanged(); } }
        public string SoundField { get => soundField; set { soundField = value; RaisePropertyChanged(); } }
        public string Tinnitus { get => tinnitus; set { tinnitus = value; RaisePropertyChanged(); } }
        public string Strength { get => strength; set { strength = value; RaisePropertyChanged(); } }
        public string DeafAidLeftModel { get => deafAidLeftModel; set { deafAidLeftModel = value; RaisePropertyChanged(); } }
        public string DeafAidRightModel { get => deafAidRightModel; set { deafAidRightModel = value; RaisePropertyChanged(); } }
        public string DeafAidVolume { get => deafAidVolume; set { deafAidVolume = value; RaisePropertyChanged(); } }
        public string DeviceWT { get => deviceWT; set { deviceWT = value; RaisePropertyChanged(); } }
        public string Chengxu { get => chengxu; set { chengxu = value; RaisePropertyChanged(); } }



        private void CancelAddMember()
        {
            //需要跳转页面
            // db.AddMember(new Model.User() { Uid = (new Random(111)).ToString() });

            DMSkin.Core.Broadcast.PushBroadcast("NavigationBack", "UserInfoViewModel");
        }

        private void SaveMember()
        {
            if (Name.IsNullOrEmpty())
            {
                var result = MessageBoxX.Show("请填写成员姓名", "提醒", Application.Current.MainWindow, MessageBoxButton.OK, new Panuon.UI.Silver.Core.MessageBoxXConfigurations()
                {
                    MessageBoxStyle = MessageBoxStyle.Modern,
                    MessageBoxIcon = MessageBoxIcon.Warning,
                    ButtonBrush = "#F1C825".ToColor().ToBrush(),
                });

                return;
            }



            if (Age.IsNullOrEmpty())
            {
                var result = MessageBoxX.Show("请填写成员年龄", "提醒", Application.Current.MainWindow, MessageBoxButton.OK, new Panuon.UI.Silver.Core.MessageBoxXConfigurations()
                {
                    MessageBoxStyle = MessageBoxStyle.Modern,
                    MessageBoxIcon = MessageBoxIcon.Warning,
                    ButtonBrush = "#F1C825".ToColor().ToBrush(),
                });

                return;
            }
            else
            {
                Int32 res = 0;
                if (false == Int32.TryParse(Age, out res) || res < 0 || res > 150)
                {
                    var result = MessageBoxX.Show("请正确填写成员年龄", "提醒", Application.Current.MainWindow, MessageBoxButton.OK, new Panuon.UI.Silver.Core.MessageBoxXConfigurations()
                    {
                        MessageBoxStyle = MessageBoxStyle.Modern,
                        MessageBoxIcon = MessageBoxIcon.Warning,
                        ButtonBrush = "#F1C825".ToColor().ToBrush(),
                    });

                    return;
                }
            }


            if (SelectMember != null)
            {

                SelectMember.Name = Name;
                SelectMember.Phone = Phone;
             
                SelectMember.Note = Zhiye;
                SelectMember.Mark = Mark;
                SelectMember.Birthday = Bday.AddYears(0 - int.Parse(Age));
                SelectMember.Age = Convert.ToInt32(Age);
                SelectMember.Gender = IsGirl == true ? 1 : 0;
                selectMember.IdCard = IdCard;
                selectMember.Insurance = Insurance;
                selectMember.Address = Address;
                selectMember.ZipCode = ZipCode;
                selectMember.AllergyHistory = AllergyHistory;
                selectMember.History = History;
                selectMember.DeafAidRoutine = DeafAidRoutine;
                selectMember.DeafAidThreshold = DeafAidThreshold;
                selectMember.SoundField = SoundField;
                selectMember.Tinnitus = Tinnitus;
                selectMember.Strength = Strength;
                selectMember.DeafAidLeftModel = DeafAidLeftModel;
                selectMember.DeafAidRightModel = DeafAidRightModel;
                selectMember.DeviceWT = DeviceWT;
                selectMember.Note = Chengxu;
                selectMember.DeafAidVolume = DeafAidVolume;
                selectMember.IdCard = IdCard;
                db.UpdateMember(SelectMember);
            }
            else
            {


                MemberInfo m = new MemberInfo();
                m.Name = Name;//(new Random()).Next(999).ToString();
                m.Uid = System.Guid.NewGuid().ToString("N");
                m.UserId = GlobalData.LoginUser.Uid;
                m.Phone = Phone;
                m.Note = Zhiye;
                m.Birthday = Bday.AddYears(0 - int.Parse(Age));
                m.Gender = IsGirl == true ? 1 : 0;
                m.Mark = Mark;
                m.Age = Convert.ToInt32(Age);

                m.IdCard = IdCard;
                m.Insurance = Insurance;
                m.Address = Address;
                m.ZipCode = ZipCode;
                m.AllergyHistory = AllergyHistory;
                m.History = History;
                m.DeafAidRoutine = DeafAidRoutine;
                m.DeafAidThreshold = DeafAidThreshold;
                m.SoundField = SoundField;
                m.Tinnitus = Tinnitus;
                m.Strength = Strength;
                m.DeafAidLeftModel = DeafAidLeftModel;
                m.DeafAidRightModel = DeafAidRightModel;
                m.DeviceWT = DeviceWT;
                m.Note = Chengxu;
                m.DeafAidVolume = DeafAidVolume;
                db.AddMember(m);

               
                if (Http.PostHost != null && Http.PostHost !="")
                {

                    var http = Http.SharedHttp();


                    //得改造一下m

                    Dictionary<string, Object> dict = new Dictionary<string, Object>();

                    //var json = JsonConvert.SerializeObject(m);
                    //var dictionary = JsonConvert.DeserializeObject<Dictionary<string, Object>>(json);

    

                    dict.Add("id", m.Uid);
                    dict.Add("address", m.Address);
                    //dict.Add("memberId", m.Uid);
                    dict.Add("age", m.Age);
                    
                    dict.Add("allergyHistory", m.AllergyHistory);
                    dict.Add("audiphone", m.DeafAidLeftModel);
                    dict.Add("audiphoneRight", m.DeafAidRightModel);
                    dict.Add("auricle", m.DeviceWT);
                    long jan1st1970ms = new DateTime(1970, 1, 1, 0, 0, 0).Ticks;//, DateTimeKind.Local
                                                                                // dict.Add("birthday", (m.Birthday.Ticks - jan1st1970ms) / 10000);


                    dict.Add("creatTime", (DateTime.Now.Ticks - jan1st1970ms) / 10000);

                    dict.Add("deafAidThreshold", m.DeafAidThreshold);
                    dict.Add("identity", m.IdCard);

                    if(m.ModifyDate == 0)
                        dict.Add("modifyDate", (System.DateTime.Now.Ticks - jan1st1970ms) / 10000);


                    string s = m.Birthday.ToString("u");
                    string s2 = s.Substring(0, s.Length - 1);
                    dict.Add("birthday", s2);

                    dict.Add("name", m.Name);
                    dict.Add("phone", m.Phone);

                    dict.Add("program", m.Note);
                    dict.Add("remarks", m.Mark);
                    dict.Add("state", m.State);

                    dict.Add("soundField", m.SoundField);
                    dict.Add("strength", m.Strength);
                    dict.Add("tinnitus", m.Tinnitus);
                    dict.Add("volume", m.DeafAidVolume);
                    dict.Add("zipCode", m.ZipCode);
                    dict.Add("sex", m.Gender);

                    if(GlobalData.LoginNetUser != null)
                    {
                        dict.Add("ordinaryUserId", GlobalData.LoginNetUser.id);
                    }
                    //                    [
                    //  {
                    //    "address": "",
                    //    "addressId": "",
                    //    "age": 0,
                    //    "allergyHistory": "",
                    //    "audiphone": "",
                    //    "audiphoneRight": "",
                    //    "auricle": "",
                    //    "birthday": "",
                    //    "cooperationId": "",
                    //    "creatTime": "",
                    //    "deafAidThreshold": "",
                    //    "disabilityGrade": "",
                    //    "disabilityTime": "",
                    //    "diseaseId": "",
                    //    "diseaseName": "",
                    //    "diseaseReason": "",
                    //    "id": "",
                    //    "identity": "",
                    //    "latitudeLongitude": "",
                    //    "modifyDate": "",
                    //    "name": "",
                    //    "ordinaryUserId": "",
                    //    "phone": "",
                    //    "portrait": "",
                    //    "program": "",
                    //    "relationship": "",
                    //    "remarks": "",
                    //    "sex": 0,
                    //    "socialSecurity": "",
                    //  
                    //"soundField": "",
                    //    "state": 0,
                    //    "strength": "",
                    //    "tinnitus": "",
                    //    "tympanitis": "",
                    //    "volume": "",
                    //    "zipCode": ""
                    //  }
                    //]
                    //                    address 住址      false
                    //string
                    //addressId   地址编号        false
                    //string
                    //age 年龄      false
                    //integer(int32)
                    //allergyHistory 过敏史     false
                    //string
                    //audiphone   助听器型号 左     false
                    //string
                    //audiphoneRight  助听器型号 右     false
                    //string
                    //auricle 耳蜗型号        false
                    //string
                    //birthday    生日      false
                    //string(date - time)
                    //cooperationId 合作方编号       false
                    //string
                    //creatTime   创建时间        false
                    //string(date - time)
                    //deafAidThreshold 助听听阈        false
                    //string
                    //disabilityGrade 评残等级        false
                    //string
                    //disabilityTime  评残时间        false
                    //string(date - time)
                    //diseaseId 疾病史     false
                    //string
                    //diseaseName 疾病名称        false
                    //string
                    //diseaseReason   疾病原因        false
                    //string
                    //id  编号      false
                    //string
                    //identity    身份证 残疾证     false
                    //string
                    //latitudeLongitude   经纬度     false
                    //string
                    //modifyDate  修改时间        false
                    //string(date - time)
                    //name 名称      false
                    //string
                    //ordinaryUserId  用户      false
                    //string
                    //phone   手机号     false
                    //string
                    //portrait    头像图片路径      false
                    //string
                    //program 程序      false
                    //string
                    //relationship    和客户的关系      false
                    //string
                    //remarks 备注      false
                    //string
                    //sex 性别      false
                    //integer(int32)
                    //socialSecurity 社保号     false
                    //string
                    //soundField  声场      false
                    //string
                    //state   0为正常，1为删除       false
                    //integer(int32)
                    //strength 强度      false
                    //string
                    //tinnitus    耳鸣匹配        false
                    //string
                    //tympanitis  中耳炎     false
                    //string
                    //volume  音量      false
                    //string
                    //zipCode 邮编      false
                    //string


                    //dictionary["Id"]= m.Uid;

                    Object[] array = new Object[1];
                    array[0] = dict;

                    StringContent jsonContent = new StringContent(JsonConvert.SerializeObject(array), Encoding.UTF8,"application/json");


#if DEBUG1
                    string result = http.GetJSonResponse(JsonConvert.SerializeObject(array), Http.PostHost + "tlyht/formal/tlj/uploadMemberList", "post");
#else
                    string result = http.GetJSonResponse(JsonConvert.SerializeObject(array), Http.PostHost + "tlyht/AudiometerTest/uploadMemberList", "post");
#endif         


                    if (result != null)
                    {
                        Console.WriteLine(result);

                        JObject o = (JObject)JsonConvert.DeserializeObject(result);

                        if (null == Http.errorWithJsonObject(o))
                        {
                            Notice.Show("用户信息已发送.", "提示", 3, MessageBoxIcon.Success);
                            Console.WriteLine("用户数据已发送到对接地址");
                            //    IList<MemberNetInfo> listOrder = new List<MemberNetInfo>();


                            //    listOrder = JsonConvert.DeserializeObject<IList<MemberNetInfo>>(o["Persons"].ToString());

                            //    if (listOrder.Count <= 0)

                            //    {
                            //        // Log4.WriteLog("没有获取到可以写入的数据记录");
                            //        return;
                            //    }
                            //    //for (int i = 0; i < listOrder.Count(); i++)
                            //    //{

                            //    //    //循环解析每一个实体
                            //    //    MemberNetInfo info = listOrder[i];

                            //    //    MemberInfo m = db.GetOneMemberByUid(info.id);

                            //    //    if (m == null)
                            //    //        m = new MemberInfo();

                            //    //    m.Uid = info.id;
                            //    //    m.UserId = info.ordinaryUserId;
                            //    //    m.Name = info.name;
                            //    //    m.Phone = info.phone;
                            //    //    m.Note = info.relationship;
                            //    //    m.Mark = info.remarks;
                            //    //    System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));//当地时区
                            //    //    var time = startTime.AddSeconds(Convert.ToDouble(info.birthday) / 1000);
                            //    //    m.Birthday = time;
                            //    //    m.Age = Convert.ToInt32((DateTime.Now.Year - time.Year));
                            //    //    //Convert.ToInt32(info.age);
                            //    //    m.Gender = info.sex.Equals("0") ? 1 : 0;
                            //    //    //m.IdCard = IdCard;
                            //    //    //m.Insurance = Insurance;
                            //    //    m.Address = info.address;
                            //    //    m.ZipCode = info.zipcode;
                            //    //    //m.AllergyHistory = AllergyHistory;
                            //    //    //m.History = History;
                            //    //    //m.DeafAidRoutine = DeafAidRoutine;
                            //    //    //m.DeafAidThreshold = DeafAidThreshold;
                            //    //    //m.SoundField = SoundField;
                            //    //    //m.Tinnitus = Tinnitus;
                            //    //    //m.Strength = Strength;
                            //    //    //m.DeafAidLeftModel = DeafAidLeftModel;
                            //    //    //m.DeafAidRightModel = DeafAidRightModel;
                            //    //    //m.DeviceWT = DeviceWT;
                            //    //    //m.Note = Chengxu;
                            //    //    //m.DeafAidVolume = DeafAidVolume;
                            //    //    //m.IdCard = IdCard;
                            //    //    db.UpdateMember(m);

                            //    //}

                            //}
                            //else
                            //{
                            //    //this.Report = Http.errorWithJsonObject(o) + ",请重试!";
                            //}
                        }


                        }



                    }



                DMSkin.Core.Broadcast.PushBroadcast("NavigationBack", "UserInfoViewModel");
            }
        }
    }
}
